package com.eleadin.ruleengine.controller;

import com.alibaba.fastjson.JSONObject;
import com.eleadin.ruleengine.service.vo.test.RuleVO;
import com.eleadin.ruleengine.token.NoneAuth;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Log4j2
@RestController
@RequestMapping("test")
public class TestController {

    @NoneAuth
    @PostMapping("/getResult")
    public Map<String, Object> getResult() {
        List<RuleVO> ruleVOS = readExcel();
        if (CollectionUtils.isEmpty(ruleVOS)) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        try {
            for (RuleVO ruleVO : ruleVOS) {
                Class catClass = Class.forName(ruleVO.getClassPath());
                Method[] declaredMethods = catClass.getDeclaredMethods();
                for (Method met : declaredMethods) {
                    if (!met.getName().equals(ruleVO.getFunctionName())) {
                        continue;
                    }
                    Class<?> params[] = met.getParameterTypes();
                    Object[] objects = new Object[params.length];
                    for (int x = 0; x < params.length; x++) {
                        objects[x] = JSONObject.parseObject(ruleVO.getReqParam());
                    }
                    Map<String, Object> invoke = (Map<String, Object>) met.invoke(catClass.newInstance(), objects);
                    map.putAll(invoke);
                }
            }
        } catch (Exception e) {
            log.info(e);
        }

        return map;
    }



    public List<RuleVO> readExcel() {
        String path = "/templates/报表1.xlsx";
        List<RuleVO> ruleVOS = new ArrayList<>();
        try {
			/*// 如果需要通过URL获取资源的加上以下的代码，不需要的省略就行
			URL url = new URL(strURL);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			// 设置超时间为3秒
			conn.setConnectTimeout(3*1000);
			// 防止屏蔽程序抓取而返回403错误
			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			// 获取输入流
			InputStream inputStream = conn.getInputStream();
			......*/

            // 获取文件输入流
            InputStream inputStream  = this.getClass().getResourceAsStream(path);
            // 定义一个org.apache.poi.ss.usermodel.Workbook的变量
            Workbook workbook = null;
            // 截取路径名 . 后面的后缀名，判断是xls还是xlsx
            // 如果这个判断不对，就把equals换成 equalsIgnoreCase()
            if (path.substring(path.lastIndexOf(".") + 1).equals("xls")) {
                workbook = new HSSFWorkbook(inputStream);
            } else if (path.substring(path.lastIndexOf(".") + 1).equals("xlsx")) {
                workbook = new XSSFWorkbook(inputStream);
            }

            // 获取第一张表
            Sheet sheet = workbook.getSheetAt(0);
            // sheet.getPhysicalNumberOfRows()获取总的行数
            // 循环读取每一行
            for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
                RuleVO ruleVO = new RuleVO();
                // 循环读取每一个格
                Row row = sheet.getRow(i);
                // row.getPhysicalNumberOfCells()获取总的列数
                for (int index = 0; index < row.getPhysicalNumberOfCells(); index++) {
                    // 获取数据，但是我们获取的cell类型
                    //代码上的内容自己根据实际需要自己调整就可以，这里只是展示一个样式···~
                    Cell cell = row.getCell(index);
                    // 转换为字符串类型
                    cell.setCellType(CellType.STRING);
                    if (index == 0) {
                        // 获取得到字符串
                        ruleVO.setClassPath(cell.getStringCellValue());
                    } else if (index == 1) {
                        // 获取得到字符串
                        ruleVO.setFunctionName(cell.getStringCellValue());
                    } else if (index == 2) {
                        // 获取得到字符串
                        ruleVO.setReqParam(cell.getStringCellValue());
                    }

                }
                ruleVOS.add(ruleVO);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ruleVOS;
    }
}
